// 广告功能禁用补丁 - 用于快手小游戏调试
// 此脚本会禁用所有广告相关功能，避免广告API不存在导致的错误

// 防止重复加载
if ((globalThis as any).__adPatchLoaded) {
  console.log('广告补丁已加载，跳过重复加载');
} else {
  (globalThis as any).__adPatchLoaded = true;

  // 确保window对象存在
  if (typeof window !== 'undefined' && window) {
    // 检查是否为快手环境
    const isKuaishou = typeof (window as any).ks !== 'undefined';
    
    if (isKuaishou) {
      console.log('检测到快手环境，使用快手原生API');
    } else {
      console.log('非快手环境，使用模拟API');
      
      // 创建安全的wx对象，避免与现有对象冲突
      if (!(window as any).wx) {
        (window as any).wx = {};
      }
      
      const wx = (window as any).wx;
    
    // 创建安全的模拟广告方法
    const createSafeAdMock = (): any => ({
      show: () => {
        console.log('模拟广告显示');
        return Promise.resolve();
      },
      hide: () => {
        console.log('模拟广告隐藏');
        return Promise.resolve();
      },
      load: () => {
        console.log('模拟广告加载');
        return Promise.resolve();
      },
      destroy: () => {
        console.log('模拟广告销毁');
      },
      onLoad: () => {},
      onClose: () => {},
      onError: () => {},
      onResize: () => {},
      style: { left: 0, top: 0, width: 320, height: 50, realWidth: 320, realHeight: 50 }
    });
    
    // 只添加不存在的广告API
    if (!wx.createRewardedVideoAd) {
      wx.createRewardedVideoAd = () => {
        const ad = createSafeAdMock();
        // 添加激励视频特有的回调处理
        let onCloseCallback: Function | null = null;
        (ad as any).onClose = (callback: Function) => {
          onCloseCallback = callback;
        };
        const originalShow = ad.show;
        (ad as any).show = () => {
          console.log('模拟激励视频广告播放');
          setTimeout(() => {
            if (onCloseCallback) {
              onCloseCallback({ isEnded: true });
            }
          }, 500);
          return Promise.resolve();
        };
        return ad;
      };
    }
    
    if (!wx.createInterstitialAd) {
      wx.createInterstitialAd = () => createSafeAdMock();
    }
    
    if (!wx.createBannerAd) {
      wx.createBannerAd = () => createSafeAdMock();
    }
    
    if (!wx.createCustomAd) {
      wx.createCustomAd = () => createSafeAdMock();
    }
    
    // 系统信息API
    if (!wx.getSystemInfoSync) {
      wx.getSystemInfoSync = () => ({
        windowWidth: 375,
        windowHeight: 667,
        pixelRatio: 2,
        statusBarHeight: 20
      });
    }
    
    // 分享相关API
    if (!wx.shareAppMessage) {
      wx.shareAppMessage = (options: any) => {
        console.log('模拟分享消息');
        if (options && options.success) {
          setTimeout(() => options.success(), 100);
        }
      };
    }
    
    if (!wx.onShow) {
      wx.onShow = (callback: Function) => {
        console.log('模拟onShow注册');
        // 可以选择是否触发回调，这里暂时不触发
      };
    }
    
    // 游戏圈按钮API
    if (!wx.createGameClubButton) {
      wx.createGameClubButton = (options: any) => {
        console.log('模拟创建游戏圈按钮');
        return {
          show: () => {
            console.log('模拟显示游戏圈按钮');
          },
          hide: () => {
            console.log('模拟隐藏游戏圈按钮');
          },
          destroy: () => {
            console.log('模拟销毁游戏圈按钮');
          },
          style: options && options.style ? options.style : {
            left: 10,
            top: 55,
            width: 35,
            height: 35
          }
        };
      };
    }
    
    // 用户信息相关API
    if (!wx.getSetting) {
      wx.getSetting = (options: any) => {
        console.log('模拟获取设置');
        const mockAuthSetting = {
          'scope.userInfo': true
        };
        if (options && options.success) {
          setTimeout(() => options.success({ authSetting: mockAuthSetting }), 100);
        }
      };
    }
    
    if (!wx.getUserInfo) {
      wx.getUserInfo = (options: any) => {
        console.log('模拟获取用户信息');
        const mockUserInfo = {
          avatarUrl: 'https://example.com/avatar.jpg',
          city: '深圳',
          country: '中国',
          gender: 1,
          language: 'zh_CN',
          nickName: '用户',
          province: '广东'
        };
        if (options && options.success) {
          setTimeout(() => options.success({ 
            userInfo: mockUserInfo,
            rawData: JSON.stringify(mockUserInfo),
            signature: 'mock_signature',
            encryptedData: 'mock_encrypted_data',
            iv: 'mock_iv'
          }), 100);
        }
      };
    }
    
    if (!wx.createUserInfoButton) {
      wx.createUserInfoButton = (options: any) => {
        console.log('模拟创建用户信息按钮');
        return {
          show: () => console.log('模拟显示用户信息按钮'),
          hide: () => console.log('模拟隐藏用户信息按钮'),
          destroy: () => console.log('模拟销毁用户信息按钮'),
          onTap: () => {},
          offTap: () => {}
        };
      };
    }
    
    if (!wx.setUserCloudStorage) {
      wx.setUserCloudStorage = (options: any) => {
        console.log('模拟设置用户云存储');
        if (options && options.success) {
          setTimeout(() => options.success(), 100);
        }
      };
    }
    
    if (!wx.postMessage) {
      wx.postMessage = (message: any) => {
        console.log('模拟发送消息到开放域:', message);
      };
    }
    
    if (!wx.showShareMenu) {
      wx.showShareMenu = (options: any) => {
        console.log('模拟显示分享菜单');
        if (options && options.success) {
          setTimeout(() => options.success(), 100);
        }
      };
    }
    
    if (!wx.onShareAppMessage) {
      wx.onShareAppMessage = (callback: Function) => {
        console.log('模拟注册分享回调');
        // 可以选择是否存储回调以便后续调用
      };
    }
    
    // 存储API - 只在不存在时添加，并确保与localStorage兼容
    if (!wx.setStorage) {
      wx.setStorage = (options: any) => {
        try {
          const value = typeof options.data === 'string' ? options.data : JSON.stringify(options.data);
          localStorage.setItem(options.key, value);
          if (options.success) setTimeout(() => options.success(), 0);
        } catch (e) {
          console.error('模拟存储失败:', e);
          if (options.fail) setTimeout(() => options.fail(e), 0);
        }
      };
    }
    
    if (!wx.getStorageSync) {
      wx.getStorageSync = (key: string) => {
        try {
          const data = localStorage.getItem(key);
          if (data === null) return '';
          try {
            return JSON.parse(data);
          } catch {
            return data;
          }
        } catch (e) {
          console.error('模拟获取存储失败:', e);
          return '';
        }
      };
    }
    
    if (!wx.clearStorage) {
      wx.clearStorage = () => {
        try {
          localStorage.clear();
        } catch (e) {
          console.error('模拟清理存储失败:', e);
        }
      };
    }
    } // 闭合非快手环境的if语句
  }
  
  console.log('广告功能禁用补丁已加载');
  
  // 添加全局错误处理器，捕获遗漏的API调用
  const originalConsoleError = console.error;
  console.error = function(...args) {
    const message = args.join(' ');
    if (message.includes('is not a function') && message.includes('wx.')) {
      console.log('检测到wx API调用错误，已被捕获:', message);
      // 不让错误传播，避免游戏崩溃
      return;
    }
    originalConsoleError.apply(console, args);
  };
}
